<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss"
                        type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                        :default-time="['00:00:00', '23:59:59']"/>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker v-model="queryParams.startTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss"
                        type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                        :default-time="['00:00:00', '23:59:59']"/>
      </el-form-item>
      <el-form-item label="结束时间" prop="entTime">
        <el-date-picker v-model="queryParams.entTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss"
                        type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                        :default-time="['00:00:00', '23:59:59']"/>
      </el-form-item>
      <el-form-item label="拼团名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入拼团名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable size="small">
          <el-option label="未审核" :value="0"/>
          <el-option label="上架" :value="1"/>
          <el-option label="下架" :value="2"/>
          <el-option label="已结束" :value="3"/>
        </el-select>
      </el-form-item>

      <el-form-item label="是否单独购买" prop="isAlone">
        <el-select v-model="queryParams.isAlone" placeholder="是否单独购买" clearable size="small">
          <el-option label="否" :value="0"/>
          <el-option label="是" :value="1"/>
        </el-select>
      </el-form-item>

      <el-form-item label="是否自动成团" prop="isGroup">
        <el-select v-model="queryParams.isGroup" placeholder="是否单独购买" clearable size="small">
          <el-option label="否" :value="0"/>
          <el-option label="是" :value="1"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">添加拼团活动</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <!-- <el-table-column label="id主键" align="center" prop="id" /> -->
      <el-table-column label="活动名称" align="center" prop="details" width="200" />

      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="商品详情" align="center" prop="goodsInfo" /> -->
      <!-- <el-table-column label="拼团名称" align="center" prop="name" /> -->
      <el-table-column label="活动开始时间" align="center" prop="startTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动结束时间" align="center" prop="entTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.entTime) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="已售库存" align="center" prop="actNum" /> -->
      <!-- <el-table-column label="剩余库存" align="center" prop="soldNum" /> -->
      <el-table-column label="商品名称" align="center" prop="goodsName"/>
      <el-table-column label="图片" align="center" prop="img" width="130">
        <template v-slot="scope">
          <div class="imgbox" v-if="scope.row.img.length !== 0">
            <img class="imgstyle" :src="scope.row.img[scope.row.imgIndex]" alt="">
            <div class="toleftstyle" @click="toleft(scope.$index,scope.row.img.length,scope.row.imgIndex)"><i
              class="el-icon-arrow-left"></i></div>
            <div class="torightstyle" @click="toright(scope.$index,scope.row.img.length,scope.row.imgIndex)"><i
              class="el-icon-arrow-right"></i></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="活动设定库存" align="center" prop="setUpNum"/>

      <el-table-column label="活动状态" align="center" prop="status">
        <template v-slot="scope">
          <span>{{ groupGoodsOrder[scope.row.status] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="成团人数" align="center" prop="groupPerson"/>
      <!--      <el-table-column label="拼团有效期" align="center" prop="groupHour" />-->
      <el-table-column label="是否单独购买" align="center" prop="isAlone">
        <template v-slot="scope">
          <span>{{ isAlone[scope.row.isAlone] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否自动成团" align="center" prop="isGroup">
        <template v-slot="scope">
          <span>{{ isGroup[scope.row.isGroup] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center">
        <template v-slot="scope">
          <el-button v-show="true" size="mini" type="text" icon="el-icon-edit"
                     @click="isTopBottom(scope.row)">{{ isTopBottomObj[scope.row.status] }}
          </el-button>
          <el-button v-show="scope.row.status === 0" size="mini" type="text" icon="el-icon-edit"
                     @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="selectById(scope.row)">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="selectById1(scope.row)">修改活动名称</el-button>
          <el-button v-show="scope.row.status === 3" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">隐藏</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="addGroupInfoFrame(scope.row)">添加拼团记录
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加拼团记录对话框 -->
    <el-dialog :title="title" :visible.sync="addGroupInfo" width="50%" @close="testClose" v-dialogDrag append-to-body>

      <div class="testUser">
        <span style="font-size: 17px;font-weight: 500;padding-right: 20px">
          商品名称:{{ testRow.goodsName }}
        </span>
        <br>
        <span style="font-size: 17px;font-weight: 500;padding-right: 20px">成团人数:{{ testRow.groupPerson }} </span>
        <span style="font-size: 17px;font-weight: 500;padding-right: 20px">已拼团人数:{{ testRow.buyPerson }}</span>
      </div>

      <!--      <el-table type="selection" tooltip-effect="dark" @selection-change="handleSelectionChange"  :data="testList" style="width: 100%">-->
      <el-table type="selection" tooltip-effect="dark" @selection-change="handleSelectionChange" ref="multipleTable"
                :data="testList" style="width: 100%">
        <el-table-column type="selection" width="55"/>

        <el-table-column label="用户名称" align="center" prop="nickName"/>
        <el-table-column label="图片" align="center" prop="avatar">
          <template v-slot="scope">
            <img :src="scope.row.avatar" style="width: 70px;height: 70px">
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        width="30%"
        title="添加用户"
        :visible.sync="addUserShow"
        append-to-body>
        <el-form ref="addUserform" :model="addUserform" label-width="120px">
          <el-form-item label="名称" prop="name">
            <el-input v-model="addUserform.name" placeholder="请输入名称"/>
          </el-form-item>
          <el-form-item label="头像" prop="url">
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="actives"
              :headers="headers"
              :http-request="(e)=>uploadSectionFile(e,1)"
              :on-remove="handleRemove"
              :file-list="filelist"
              :limit="1"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">图片大小不能超过 10 M</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addUserformFun">确 定</el-button>
          <el-button @click="addUserShow = false">取 消</el-button>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer flexs">
        <el-button type="primary" @click="addUser">添加用户</el-button>
        <div>
          <el-button type="primary" @click="testSubmitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>

    </el-dialog>

    <!-- 修改拼团名称 -->
    <el-dialog :title="title" :visible.sync="groupName" width="80%" v-dialogDrag append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="拼团描述" prop="details">
          <el-input v-model="form.details" placeholder="请输入拼团描述"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="title !== '查看拼团商品'" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="80%" v-dialogDrag append-to-body>
      <el-dialog
        width="60%"
        title="商品"
        :visible.sync="innerVisible"
        @close="productRefcColse"
        append-to-body>
        <el-table ref="productRef" :data="Goodslist" @selection-change="productSelection">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="id" align="center" prop="id"/>
          <el-table-column label="商品名称" align="center" prop="name"/>
          <el-table-column label="图片" align="center" prop="img">
            <template v-slot="scope">
              <div class="imgbox" v-if="scope.row.img.length !== 0">
                <img class="imgstyle" :src="scope.row.img[scope.row.imgIndex]" alt="">
                <div class="toleftstyle" @click="toleft(scope.$index,scope.row.img.length,scope.row.imgIndex)"><i
                  class="el-icon-arrow-left"></i></div>
                <div class="torightstyle" @click="toright(scope.$index,scope.row.img.length,scope.row.imgIndex)"><i
                  class="el-icon-arrow-right"></i></div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品分类" align="center" prop="type">
            <template v-slot="scope">
              <span>{{ gettype(scope.row.type) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="销售数量" align="center" prop="saleNum"/>
          <el-table-column label="商品上架状态" align="center" prop="status">
            <template v-slot="scope">
              <el-tag :type="scope.row.status == 1 ? 'success' : 'info'" effect="dark">
                {{ statusobj[scope.row.status] }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="Goodslisttotal > 0" :total="Goodslisttotal" :page.sync="goodsQueryParams.pageNo"
                    :limit.sync="goodsQueryParams.pageSize"
                    @pagination="getGoodsList"/>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="pichangeimgSortConfirm">确 定</el-button>
          <el-button @click="innerVisible = false">取 消</el-button>

        </span>
      </el-dialog>



      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="商品名称" prop="goodsId">
          <el-select v-model="form.goodsId" :disabled="form.id" filterable remote reserve-keyword
                     placeholder="请输入关键词"
                     :remote-method="remoteMethod" @change="productNameChange">
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-button @click="lookProduct" style="margin-left:10px" type="primary">查看</el-button>
        </el-form-item>
        <el-form-item label="商品图片" prop="goodsInfo">
          <img style="width:100px;height:120px" :src="form.zhanimg" alt="">
        </el-form-item>
        <el-form-item label="拼团描述" prop="details">
          <el-input v-model="form.details" placeholder="请输入拼团描述"/>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable v-model="form.startTime" type="date" value-format="timestamp"
                          placeholder="选择开始时间"/>
        </el-form-item>
        <el-form-item label="结束时间" prop="entTime">
          <el-date-picker clearable v-model="form.entTime" type="date" value-format="timestamp"
                          placeholder="选择结束时间"/>
        </el-form-item>
        <el-form-item label="拼团人数" prop="groupPerson">
          <el-input v-model="form.groupPerson" placeholder="请输入拼团人数"/>
        </el-form-item>

        <el-form-item label="拼团名称" prop="groupId">
          <el-select v-model="form.groupId" @change="tuanChange" placeholder="拼团名称" clearable size="small">
            <el-option v-for="item in tuanList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否允许单独购买" prop="isAlone">
          <el-radio-group v-model="form.isAlone">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否自动成团" prop="isGroup">
          <el-radio-group v-model="form.isGroup">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-table ref="myTable" :data="form.goodsInfo" border style="width: 70%">
          <el-table-column prop="" label="" type="expand" width="30">
            <template v-slot="scope">
              <el-table :data="scope.row.child" border style="width: 100%">
                <el-table-column prop="size" label="尺码">
                  <template v-slot="scop">
                    <div>
                      <el-input v-model="scop.row.size" disabled placeholder="请输入内容"></el-input>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="价格">
                  <template v-slot="scop">
                    <div>
                      <el-input v-model="scop.row.price" disabled placeholder="请输入内容"></el-input>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="num" label="库存数量">
                  <template v-slot="scop">
                    <div>
                      <el-input v-model="scop.row.num" disabled placeholder="请输入内容"></el-input>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="weight" label="重量">
                  <template v-slot="scop">
                    <div style="display:flex;align-items:center;">
                      <el-input v-model="scop.row.weight" disabled placeholder="请输入内容"></el-input>
                      <span style=" white-space: nowrap;">kg</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="groupPrice" label="拼团价格">
                  <template v-slot="scop">
                    <div>
                      <el-input v-model="scop.row.groupPrice" placeholder="请输入内容"></el-input>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="groupNum" label="拼团活动数量">
                  <template v-slot="scop">
                    <div>
                      <el-input v-model="scop.row.groupNum" placeholder="请输入内容"></el-input>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="url" label="图片">
            <template v-slot="scope">
              <div>
                <img style="width:50px;height:50px;" :src="scope.row.url" alt="">
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="title !== '查看拼团商品'" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createGroupGoods,
  updateGroupGoods,
  deleteGroupGoods,
  getGroupGoods,
  getGroupGoodsPage,
  exportGroupGoodsExcel,
  getLotteryUser
} from "@/api/qd/groupGoods";
import {getGoodsPage} from "@/api/qd/goods";

export default {
  name: "GroupGoods",
  components: {},
  data() {
    return {
      groupName:false,
      actives: process.env.VUE_APP_BASE_API + '/pc/file/upload',
      headers: {Authorization: 'Bearer ' + localStorage.getItem('ACCESS_TOKEN')},
      //确认按钮显示
      isSelect: true,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 拼团商品列表
      list: [],
      // 测试用户总条数
      testTotal: 0,
      // 测试用户列表
      testList: [],
      //多选的列表
      handDate: [],
      //选中的行
      testRow: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      addGroupInfo: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        createTime: [],
        goodsId: null,
        goodsInfo: null,
        name: null,
        groupId: null,
        startTime: [],
        entTime: [],
        actNum: null,
        soldNum: null,
        status: null,
        groupPerson: null,
        groupHour: null,
        isAlone: null,
        isGroup: null,
        img: null
      },
      // 表单参数
      form: {},
      //活动状态 0未审核1上架2下架3已结束
      groupGoodsOrder: {0: '未审核', 1: '上架', 2: '下架', 3: '已结束'},
      //是否单独购买
      isAlone: {0: '否', 1: '是'},
      //是否自动成团
      isGroup: {0: '否', 1: '是'},
      // 表单校验
      rules: {
        goodsId: [{required: true, message: "商品名称不能为空", trigger: "blur"}],
        groupPerson: [{required: true, message: "拼团人数不能为空", trigger: "blur"}],
        isAlone: [{required: true, message: "是否允许单独购买不能为空", trigger: "change"}],
        isGroup: [{required: true, message: "是否自动成团不能为空", trigger: "change"}],
        groupId: [{required: true, message: "拼团名称不能为空", trigger: "change"}],
        startTime: [{required: true, message: "开始时间不能为空", trigger: "blur"}],
        entTime: [{required: true, message: "结束时间不能为空", trigger: "blur"}],
      },
      productOptions: [],
      productForm: {},
      tuanList: [],
      isTopBottomObj: {0: '上架', 1: '下架', 2: '上架',3:'下架'},
      // 内嵌商品表格
      Goodslist: [],
      Goodslisttotal: 0,
      goodsQueryParams: {
        pageNo: 1,
        pageSize: 10,
      },
      innerVisible: false, // 内嵌商品表格渲染
      options: [],
      statusobj: {1: '上架', 2: '下架'},
      multipleSelection: [],
      // 添加用户
      addUserShow: false,
      filelist: [],
      addUserform: {}
    };
  },
  created() {
    this.getList();
    this.getOtherData()
    this.getTestUser()
    // 获取内嵌商品表格数据
    this.getGoodsList()
    this.fenleiList()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getGroupGoodsPage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.list.forEach(item=>{
          this.$set(item,'imgIndex',0)
        })
        this.total = response.data.total;
        this.loading = false;
      });
    },
    addUser() { // 添加用户
      this.addUserform = {}
      this.addUserShow = true
    },
    addUserformFun() {// 添加用户确认按钮
      if (!this.addUserform.name) return this.$message.warning('请填写名称')
      if (this.filelist.length === 0) return this.$message.warning('请上传头像')
      this.addUserform.url = this.filelist[0].url
      this.$axios({url: '/qd/lottery/addLotteryUser', method: 'get', params: {...this.addUserform}}).then(res => {
        this.$message.success('操作成功')
        this.getTestUser()
        this.addUserShow = false
      })
    },
    uploadSectionFile(val, pan) {  // 上传图片请求
      let file = val.file
      let size = file.size / 1024 / 1024;
      if (size > 10) {
        return this.$message.warning('图片大小不能超过 10 M')
      }
      // 根据后台需求数据格式
      const form = new FormData();
      // 文件对象
      form.append("multipartFile", file);
      // 本例子主要要在请求时添加特定属性，所以要用自己方法覆盖默认的action
      // form.append("clientType", 'xxx');
      // 项目封装的请求方法，下面做简单介绍
      this.$axios({url: '/pc/file/upload', method: 'post', data: form}).then(res => {

        // this.addUserform.url = res.data
        this.filelist = [{url: res.data}]
        this.$message.success('上传成功')
      })
        .catch(() => {
          // xxx
        });
    },
    // 移除图片时
    handleRemove(file, fileList) {
      this.filelist = fileList
    },
    getGoodsList() {
      //  获取商品数据
      getGoodsPage(this.goodsQueryParams).then(response => {
        this.Goodslist = response.data.list ?? [];
        this.Goodslist.forEach(item => {
          this.$set(item, 'imgIndex', 0)
          this.$set(item, 'check', false)
        })
        this.Goodslisttotal = response.data.total;
        this.loading = false;
      });
    },
    pichangeimgSortConfirm() {
      if (this.multipleSelection.length !== 1) return this.$message.warning('请选中一种商品')

      const obj = this.multipleSelection[0]
      if (obj.img && obj.img.length !== 0) this.$set(this.form, 'zhanimg', obj.img[0])
      this.productOptions.push({...obj})
      if (obj.specif && obj.specif.length !== 0) this.productopen()
      this.$set(this.form, 'goodsId', obj.id ?? '')
      this.$set(this.form, 'goodsInfo', obj.specif ?? [])
      this.innerVisible = false
    },
    fenleiList() {
      // 获取商品分类数据
      this.$axios({url: 'qd/goodsType/getTree', method: 'get'}).then(res => {
        this.options = res.data ?? []
        // 删除第三层级的children
        this.options.forEach(item => {
          item.children.forEach(ite => {
            ite.children.forEach(it => {
              delete it.children
            })
          })
        })
      })
    },
    lookProduct() { // 查看商品
      this.innerVisible = true;
    },
    productopen() { // 打开表格下拉
      this.$nextTick(() => {
        this.$refs.myTable.toggleRowExpansion(this.form.goodsInfo[0], true)
      })

    },
    productRefcColse() {
      this.$refs.productRef.clearSelection()
    },
    gettype(str) {  //根据商品类型id获取值
      let a = '', b = '', c = ''
      if (str) {
        let arr = str.split(',')
        this.options.forEach(item => {
          if (item.value === Number(arr[0])) {
            a = item.label ?? ''
            item.children.forEach(ite => {
              if (ite.value === Number(arr[1])) {
                b = item.label ?? ''
                ite.children.forEach(it => {
                  if (it.value === Number(arr[2])) {
                    c = it.label ?? ''
                  }
                })
              }
            })
          }
        })
      }
      return a + b + c
    },
    toleft(index, imglength, iindex) {  // 图片向右
      if (iindex === 0) return this.Goodslist[index].imgIndex = imglength - 1 ?? 0
      this.Goodslist[index].imgIndex -= 1
    },
    toright(index, imglength, iindex) {  // 图片向左
      if (imglength - 1 === iindex) return this.Goodslist[index].imgIndex = 0
      this.Goodslist[index].imgIndex += 1
    },
    productSelection(val) {
      this.multipleSelection = val;
    },
    //获取测试用户列表
    getTestUser() {
      this.$axios({url: '/qd/lottery/getLotteryUser', method: 'get'}).then(response => {
        this.testList = response.data.list;
        this.testTotal = response.data.total;
      })
    },
    getOtherData() {
      this.$axios({url: '/qd/group-goods/findGroup', method: 'get'}).then(res => {
        this.tuanList = res.data ?? []
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.addGroupInfo = false;
      this.reset();
      this.handDate = [];
      this.isSelect = true
      this.groupName=false
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        goodsId: undefined,
        goodsInfo: undefined,
        name: undefined,
        groupId: undefined,
        startTime: undefined,
        entTime: undefined,
        actNum: undefined,
        soldNum: undefined,
        status: undefined,
        groupPerson: undefined,
        groupHour: undefined,
        isAlone: undefined,
        isGroup: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    remoteMethod(value) { // 查询商品
      this.$axios({url: '/qd/group-goods/findByName', method: 'get', params: {name: value}}).then(res => {
        this.productOptions = res.data ?? []
      })
    },
    productNameChange(e) {
      // this.form
      const obj = this.productOptions.find(item => item.id === e)
      if (obj.img && obj.img.length !== 0) this.$set(this.form, 'zhanimg', obj.img[0])
      this.$set(this.form, 'goodsInfo', obj.specif ?? [])
      if (obj.specif && obj.specif.length !== 0) this.productopen()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.isAlone = 1
      this.form.isGroup = 1
      this.open = true;
      this.title = "添加拼团商品";
    },
    isTopBottom(row) {
      if (row.status === 0 || row.status === 2) {
        this.$confirm('是否确定上架?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios({url: '/qd/group-goods/updateStatus', method: 'get', params: {type: 1, id: row.id}}).then(res => {
            this.$message({
              type: 'success',
              message: '上架成功!'
            });
            this.getList()
          })
        })
      }
      if (row.status === 1) {
        this.$confirm('是否确定下架?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios({url: '/qd/group-goods/updateStatus', method: 'get', params: {type: 2, id: row.id}}).then(res => {
            this.$message({
              type: 'success',
              message: '下架成功!'
            });
            this.getList()
          })

        })
      }
    },
    //添加拼团记录对话框
    addGroupInfoFrame(row) {
      this.testRow = row;
      this.addGroupInfo = true;

    },
    testClose() {
      this.$refs.multipleTable.clearSelection();
      this.handDate = []
      console.log(111)
      this.isSelect = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getGroupGoods(id).then(response => {
        this.form = response.data;
        if (this.form.img && this.form.img.length !== 0) {
          this.form.zhanimg = this.form.img[0]
        }

        this.open = true;
        this.title = "修改拼团商品";
      });
    },
    selectById(row) { // 查看
      this.reset();
      const id = row.id;
      getGroupGoods(id).then(response => {
        this.form = response.data;
        if (this.form.img && this.form.img.length !== 0) {
          this.form.zhanimg = this.form.img[0]
        }

        this.open = true;
        this.title = "查看拼团商品";
        if (this.form.goodsInfo && this.form.goodsInfo.length !== 0) this.productopen()
        this.isSelect = false;
      });
      //console.log(111,this.isSelect)
    },
    selectById1(row) { // 查看
      this.reset();
      const id = row.id;
      getGroupGoods(id).then(response => {
        this.form = response.data;
        if (this.form.img && this.form.img.length !== 0) {
          this.form.zhanimg = this.form.img[0]
        }

        this.groupName = true;
        this.title = "修改活动名称";
        if (this.form.goodsInfo && this.form.goodsInfo.length !== 0) this.productopen()
        this.isSelect = false;
      });
      //console.log(111,this.isSelect)
    },
    tuanChange(e) {
      this.form.name = this.tuanList.find(item => item.id === e).name
    },
    verifyField(name) {
      if (name === undefined || name === null || name === '') {
        return false
      } else {
        return true
      }
    },
    testSubmitForm() {
      this.$axios({
        url: '/qd/lottery/addTestLottery',
        method: 'post',
        data: {users: this.handDate, groupGoodsId: this.testRow.id}
      }).then(res => {
        this.$message({
          type: 'success',
          message: '添加成功!',
        });
        this.addGroupInfo = false;
        this.handDate = [];
        this.getList();
      })
    },
    handleSelectionChange(one) {
      this.handDate = one;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        let obj = JSON.parse(JSON.stringify(this.form))
        // 过滤未填写的  计算活动库存
        let nums = 0
        if (obj.goodsInfo.length !== 0) {
          let arr = obj.goodsInfo ?? []
          obj.goodsInfo = arr.filter(item => {
            item.child = item.child.filter(ite => {
              if (this.verifyField(ite.groupPrice) && this.verifyField(ite.groupNum)) {
                nums += Number(ite.groupNum)
                return true
              }
            })
            if (item.child.length !== 0) return true
          })
        }
        obj.setUpNum = nums ?? 0
        if (obj.setUpNum === 0) return this.$message.warning('未添加拼团活动库存')
        // 校验活动数量不能大于库存数量
        const a = obj.goodsInfo.some(item => {
          if (item.child instanceof Array) {
            const b = item.child.some(ite => {
              if (ite.groupNum > ite.num) return true
            })
            if (b) return true
          }

        })
        if (a) return this.$message.warning('活动数量不能大于库存数量')
        // 修改的提交
        if (obj.id != null) {
          updateGroupGoods(obj).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.groupName=false;
            this.getList();
          });
          return;
        }
        // if(Object.keys(this.productForm).length === 0) return this.$message.waring('请选择商品')
        // 添加的提交
        createGroupGoods(obj).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除拼团商品编号为"' + id + '"的数据项?').then(function () {
        return deleteGroupGoods(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有拼团商品数据项?').then(() => {
        this.exportLoading = true;
        return exportGroupGoodsExcel(params);
      }).then(response => {
        this.$download.excel(response, '拼团商品.xls');
        this.exportLoading = false;
      }).catch(() => {
      });
    }
  }
};
</script>
<style lang="scss" scoped>
@import "../../styles/minImgStyle.scss";

.flexs {
  display: flex;
  justify-content: space-between;
}
</style>
